import axios from 'axios';
import qs from 'qs'

const req = axios.create();
req.defaults.baseURL='http://127.0.0.1:8888/api/private/v1';
req.defaults.timeout = 3000;
function ajax({method='get',url,params={},headtype=''}) {

    if(url!="/login"){
        req.defaults.headers['Authorization']=window.sessionStorage.getItem('token')
    }
         
    let data = {}
    if(method.toLowerCase()=='post'){
        if(headtype=='form'){
            req.defaults.headers['content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
        
            data = params
        }else{
            req.defaults.headers['content-Type'] = 'application/json;charset=utf-8';
            data = params;

        }
    }
    if(method.toLowerCase()=='get'){
        if(headtype=='form'){
            req.defaults.headers['content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
        }
        url = url + '?' + qs.stringify(params);
    }
    if(method.toLowerCase()=='put'){
        data = params;
    }
    return new Promise((resolve,reject)=>{
        req({
            method,
            url,
            data
        }).then(res=>{
            resolve(res)
        }).catch(err=>{
            reject(err)
        })
    })
}
export default ajax